#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from datetime import datetime
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Float, Integer, Boolean, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""app_ver collection has
    id:             自增id (int)
    appver:         app版本号 (str)
    status:         该版本状态(int) (0:不可用，1:可用)
    ctime:          创建时间(datetime)
"""


class AppVerItem(object):
    """docstring for AppVerItem"""

    def to_dict(self):
        res = {}
        res['id'] = self.id
        res['appver'] = self.appver
        res['status'] = self.status
        res['ctime'] = ''
        if self.ctime:
            res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")
        return res

    def __repr__(self):
        print "version:%s operator file: %s/%s" % (self.appver, self.path, self.filename)


app_ver_table = Table(
    'app_ver', metadata,
    Column('id', Integer, primary_key=True),
    Column('appver', Unicode(12), index=True, unique=True, nullable=False),
    Column('status', Integer, default=0, nullable=False),
    Column('ctime', DateTime, default=datetime.now, nullable=False)
)

mapper(AppVerItem, app_ver_table)


def create_app_ver_table_if_not_exist():
    metadata.create_all(engine)


def add_app_ver_item(p_item):
    item = AppVerItem()
    item.appver = p_item['appver']
    item.status = p_item['status']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


'''
get all appver which status==1
'''


def get_app_ver_all_valid():
    try:
        session = Session()
        items = session.query(AppVerItem).filter(AppVerItem.status == 1).order_by(AppVerItem.id.asc()).all()
        res = []
        for item in items:
            res.append(item.to_dict())
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
get appver info by appver
'''


def get_app_ver_by_ver(p_appver):
    try:
        session = Session()
        item = session.query(AppVerItem).filter(AppVerItem.appver == p_appver).first()
        res = item.to_dict() if item else None
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
get the latest appver info
'''


def get_latest_app_ver():
    try:
        session = Session()
        item = session.query(AppVerItem).filter().order_by(AppVerItem.id.desc()).first()
        res = item.to_dict() if item else None
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
get the latest valided appver info(status == 1)
'''


def get_latest_valid_app_ver():
    try:
        session = Session()
        item = session.query(AppVerItem).filter(AppVerItem.status == 1).order_by(AppVerItem.id.desc()).first()
        res = item.to_dict() if item else None
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_vers_after_this_ver(p_appver):
    try:
        session = Session()
        item = session.query(AppVerItem).filter(AppVerItem.appver == p_appver).first()
        if not item:
            return None
        id = item.id

        items = session.query(AppVerItem).filter(AppVerItem.id > id).order_by(AppVerItem.id.asc()).all()
        if not items:
            return None
        res = []
        for item in items:
            res.append(item.to_dict())
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
update appver's status
'''


def update_status_by_app_ver(p_appver, p_status):
    if not (p_appver and p_status):
        return False
    try:
        updateField = {AppVerItem.status: p_status}
        session = Session()
        session.query(AppVerItem).filter(AppVerItem.appver == p_appver).update(updateField, synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def delete_title_by_descid(p_appver):
    try:
        session = Session()
        session.query(AppVerItem).filter(AppVerItem.appver == p_appver).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


if __name__ == "__main__":
    create_app_ver_table_if_not_exist()

    item1 = {'appver': '2.1.1', 'status': '0'}
    item2 = {'appver': '2.1.2', 'status': '0'}
    item3 = {'appver': '2.1.3', 'status': '0'}
    item4 = {'appver': '2.1.4', 'status': '0'}
    item5 = {'appver': '2.1.5', 'status': '0'}
    item6 = {'appver': '2.1.6', 'status': '0'}
    item7 = {'appver': '2.1.7', 'status': '0'}
    '''
    add_app_ver_item(item1)
    add_app_ver_item(item2)
    add_app_ver_item(item3)
    add_app_ver_item(item4)
    add_app_ver_item(item5)
    add_app_ver_item(item6)
    add_app_ver_item(item7)
    '''

    res = get_app_ver_all_valid()
    print "==========get_app_ver_all_valid():None "
    print res

    res = get_app_ver_by_ver('2.1.4')
    print "==========get_app_ver_by_ver():2.1.4 ,status:0 "
    print res

    res = get_latest_app_ver()
    print "==========get_latest_app_ver():2.1.7 ,status:0 "
    print res

    res = get_vers_after_this_ver('2.1.4')
    print "==========get_vers_after_this_ver():2.1.5, 2.1.6, 2.1.7 ,status:0 "
    print res

    update_status_by_app_ver('2.1.6', 1)
    update_status_by_app_ver('2.1.2', 1)

    res = get_latest_valid_app_ver()
    print "==========get_latest_valid_app_ver():2.1.6 ,status:1 "
    print res
